package cbh.tool.xls;

import org.stringtemplate.v4.ST;
import org.stringtemplate.v4.STGroup;

import java.io.*;
import java.util.List;

/**
 * Created by huxin on 2016/1/18.
 */
public class FileCompleteXLS {

    private STGroup stGroup;
    private File file;
    private FileOutputStream fos = null;
    private OutputStreamWriter osw = null;
    public FileCompleteXLS(STGroup xls) {
        stGroup = xls;
    }

    public void buildFile(File file) throws IOException {
        if(file.exists()){
            file.delete();
        }
        this.file =file;
        buildOWSStream();
    }

    public void writeTail() throws IOException {
        ST st = stGroup.getInstanceOf("tail");
        osw.write(st.render());
        osw.flush();
    }

    public void writeHead() throws IOException {
        ST st = stGroup.getInstanceOf("header");
        osw.write(st.render());
        osw.flush();
    }

    public void writeSheetHeader(String sheetName) throws IOException {
        ST st1 = stGroup.getInstanceOf("sheetHeader");
        st1.add("sheetName",sheetName);
        osw.write(st1.render());
    }

    public void writeSheet(String sheetName,List list) throws IOException {
        writeSheetHeader(sheetName);
        while (true) {
            if(list.size() < 2000) {
                writeRow(list);
                break;
            }
            writeRow(list.subList(0,2000));
            this.close();
            this.buildOWSStream();
            list = list.subList(2000,list.size());
        }
        writeSheetTail();
    }

    public void writeSheetTail() throws IOException {
        ST st1 = stGroup.getInstanceOf("sheetTail");
        osw.write(st1.render());
    }

    public void writeRow(List list) throws IOException {
        ST st1 = stGroup.getInstanceOf("row");
        st1.add("lists",list);
        osw.write(st1.render());
    }

    private void buildOWSStream() throws FileNotFoundException {
        if(file != null){
            fos = new FileOutputStream(file,true);
            osw = new OutputStreamWriter(fos);
        }else {
            throw new FileNotFoundException();
        }
    }

    public void close() throws IOException {
        this.fos.flush();
        this.osw.flush();
        this.fos.close();
        this.osw.close();
    }
}
